package com.spa.domain.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spa.application.command.member.MassagistEvaluateAddCommand;
import com.spa.domain.entity.MassagistEvaluate;
import com.spa.domain.entity.UserInfo;
import com.spa.infrastructure.enums.dict.base.WhetherTypeEnum;
import com.spa.infrastructure.mapper.MassagistEvaluateMapperStruct;
import com.spa.infrastructure.repository.condition.MassagistEvaluateCondition;
import com.spa.infrastructure.repository.po.MassagistEvaluatePO;
import com.spa.infrastructure.repository.po.MassagistPO;
import com.spa.infrastructure.repository.service.MassagistEvaluateRepositoryService;
import com.spa.infrastructure.repository.service.MassagistRepositoryService;
import com.spa.infrastructure.util.SessionUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 * 技师评价表  domain
 *
 * @author: lig
 * @date: 2024-01-08
 */
@Service
public class MassagistEvaluateService {

    @Resource
    private MassagistEvaluateRepositoryService massagistEvaluateRepositoryService;

    @Resource
    private MassagistRepositoryService massagistRepositoryService;
    @Resource
    private UserInfoService userInfoService;

    /**
     * 用户端 添加我的评价
     */
    @Transactional
    public boolean memberAddMy(MassagistEvaluateAddCommand command) {
        MassagistEvaluatePO massagistEvaluatePO = MassagistEvaluateMapperStruct.INSTANCE.commandMember2Po(command);
        massagistEvaluatePO.setUserId(SessionUtil.getUser().getUserId());
        //标签列表转为字符串
        massagistEvaluatePO.setTags(MassagistEvaluate.tagListToTags(command.getTagList()));
        massagistEvaluatePO.setIsDel(WhetherTypeEnum.$0.getCode());

        if (ObjectUtils.isEmpty(command.getScore())) massagistEvaluatePO.setScore(0);

        if(massagistEvaluateRepositoryService.addInfo(massagistEvaluatePO)){

            //更新技师评分
            updateMassagistEvaluate(command.getMassagistId());
            return true;
        }
        return false;
    }


    /**
     * 更新删除状态
     *
     * @param id ID
     */
    public boolean updateDelById(Long id,WhetherTypeEnum whetherType) {
        MassagistEvaluatePO po = new MassagistEvaluatePO();
        po.setId(id);
        po.setIsDel(whetherType.getCode());
        return massagistEvaluateRepositoryService.updateById(po);
    }


    @Transactional
    public MassagistEvaluatePO infoById(Long id) {
        return massagistEvaluateRepositoryService.getById(id);
    }

    public Page<MassagistEvaluate> pageListInfo(MassagistEvaluateCondition condition) {
        Page<MassagistEvaluatePO> page = massagistEvaluateRepositoryService.pageListInfo(condition);
        Page<MassagistEvaluate> pageEntity = MassagistEvaluateMapperStruct.INSTANCE.po2Entity4Page(page);

        buildBaseMassagistEvaluate(pageEntity.getRecords());
        return pageEntity;
    }

    public List<MassagistEvaluate> listInfo(MassagistEvaluateCondition condition) {
        List<MassagistEvaluatePO> list = massagistEvaluateRepositoryService.listInfo(condition);
        List<MassagistEvaluate> pageEntity = MassagistEvaluateMapperStruct.INSTANCE.po2Entity4List(list);
        buildBaseMassagistEvaluate(pageEntity);
        return pageEntity;

    }

    /**
     * 校验用户订单是否评价
     *
     * @param userId  用户ID
     * @param orderId 订单ID
     * @return true  已评价   false 未评价
     */
    public boolean verifyEvaluate(Long orderId, Long userId) {
        MassagistEvaluateCondition condition = new MassagistEvaluateCondition();
        condition.setOrderId(orderId);
        condition.setUserId(userId);
        List<MassagistEvaluatePO> poList = massagistEvaluateRepositoryService.listInfo(condition);
        if (CollUtil.isNotEmpty(poList)) {
            return true;
        }
        return false;
    }


    /**
     * 更新技师评分
     * //技师评分：默认5.0分，根据用户的评分计算得出 技师评分 =（所有的评分总和）/ 评价次数
     *
     * @author: lig
     * @date: 2024/1/16
     */
    public void updateMassagistEvaluate(Long massagistId) {

        MassagistEvaluateCondition meCondition = new MassagistEvaluateCondition();
        meCondition.setMassagistId(massagistId);
        meCondition.setIsDel(WhetherTypeEnum.$0.getCode());
        List<MassagistEvaluatePO> mePoList = massagistEvaluateRepositoryService.listInfo(meCondition);
        BigDecimal evaluateNum = new BigDecimal("1");
        BigDecimal scoreDec = BigDecimal.ZERO;
        if (CollUtil.isNotEmpty(mePoList)) {
            evaluateNum = BigDecimal.valueOf(mePoList.size());
            int totalScore = mePoList.stream().mapToInt(MassagistEvaluatePO::getScore).sum();
            scoreDec = BigDecimal.valueOf(totalScore);
        }

        MassagistPO massagistPO = new MassagistPO();
        massagistPO.setId(massagistId);
        if(scoreDec.compareTo(BigDecimal.ZERO) < 1){
            massagistPO.setScore("0");
        }else {
            //技师评分规则：技师评分 = 所有用户对该技师的评分总和 / 用户数量
            scoreDec = scoreDec.divide(evaluateNum,1,RoundingMode.UP);
            massagistPO.setScore(scoreDec.toString());
        }

        //更新技师评分
        massagistRepositoryService.updateMassagitByCondition(massagistPO);

    }

    /**
     * 构造基础 技师评价信息
     *
     * @author: lig
     * @date: 2024/1/16
     */
    private void buildBaseMassagistEvaluate(List<MassagistEvaluate> list) {
        list.stream().forEach(a -> {
            a.setTagList(MassagistEvaluate.tagsTotagList(a.getTags()));

            MassagistPO massagistPO = massagistRepositoryService.getById(a.getMassagistId());
            a.setMassagistName(massagistPO.getName());

            UserInfo userInfo = userInfoService.userInfoById(a.getUserId());
            a.setUserName(userInfo.getName());
            a.setUserAvatar(userInfo.getAvatar());

        });

    }
}
